package com.lzn.dds.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.lzn.dds.entity.DbSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author lzn
 * @date 6/8/21 8:28 PM
 */
public class DynamicDataSource {
    public static DynamicDataSource instance(){
        return DynamicDataSourceBuilder.instance;
    }
    public Connection getConnection(DbSource dbSource){
        String projectCode = DBIdentifier.getProjectCode();
        //1.获取数据源
        DruidDataSource dds = DDSHolder.instance().getDDS(projectCode);
        //2.如果不存在则创建
        if(dds == null) {
            try {
                DruidDataSource newDDS = initDDS(dbSource);
                DDSHolder.instance().addDDS(projectCode, newDDS);
            } catch (Exception e) {
                //log....
                return null;
            }
        }
        dds = DDSHolder.instance().getDDS(projectCode);
        try{
            return dds.getConnection();
        }catch (SQLException e1){
            // log
            return null;
        }

    }
    private DruidDataSource initDDS(DbSource dbSource){
        DruidDataSource dataSource = new DruidDataSource();
        if("mysql".equals(dataSource.getDbType())){
            //设置数据库启动类
            dataSource.setDriverClassName("");
            //设置数据库连接检测语句
            dataSource.setValidationQuery("select 1");
        }
        // url,user.pwd.连接池大小，等待时间，连接数，检测时间等
        return dataSource;
    }

    public static class DynamicDataSourceBuilder {
        private static DynamicDataSource instance = new DynamicDataSource();
    }
}
